import Vue from 'vue'
import Vuex from 'vuex'
import _ from 'lodash'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    SESSION_LIST: [],
    MESSAGE_LIST: {}
  },
  getters: {
    getSession: (state) => (sessionId) => {
      return state.SESSION_LIST.find(item => sessionId === item.sessionId);
    },
    countUnreadMessage: (state) => {
      let count = 0;
      state.SESSION_LIST.forEach(item => {
        count = count + item.unreadCount;
      });
      return count;
    },
    countSessionUnreadMessage: (state) => (sessionId) => {
      let session = state.SESSION_LIST.find(item => sessionId === item.sessionId);
      return session ? session.unreadCount : 0;
    },
  },
  mutations: {
    addSession(state, sessions) {
      sessions.reverse().forEach(element => {
        let index = state.SESSION_LIST.findIndex(item => element.sessionId === item.sessionId);
        if (index >= 0) {
          state.SESSION_LIST.splice(index, 1);
        }
        state.SESSION_LIST.unshift(element);
      });
    },
    coverSession(state, session) {
      if (!session) {
        return
      }
      let index = state.SESSION_LIST.findIndex(item => session.sessionId === item.sessionId);
      if (index >= 0) {
        state.SESSION_LIST.splice(index, 1, session);
      }
    },
    removeSession(state, sessionId) {
      let index = state.SESSION_LIST.findIndex(item => sessionId === item.sessionId);
      if (index >= 0) {
        state.SESSION_LIST.splice(index, 1);
      }
    },
    clearMessage(state, sessionId) {
      Vue.set(state.MESSAGE_LIST, sessionId, []);
    },
    frontMessage(state, obj) {
      let sessionId = obj.sessionId;
      let list = state.MESSAGE_LIST[sessionId];
      let arr = list ? _.clone(list) : [];
      Vue.set(state.MESSAGE_LIST, sessionId, _.concat(obj.messages, arr));
    },
    addMessage(state, message) {
      let list = state.MESSAGE_LIST[message.sessionId];
      let arr = list ? _.clone(list) : [];
      if (arr.findIndex(item => item.messageId === message.messageId) < 0) {
        arr.push(message);
        Vue.set(state.MESSAGE_LIST, message.sessionId, arr);
      }
    },
    failMessage(state, message) {
      console.log(message)
      let list = state.MESSAGE_LIST[message.sessionId];
      let arr = list ? _.clone(list) : [];
      let index = arr.findIndex(item => item.messageId === message.messageId);
      if (index >= 0) {
        message.fail = true;
        arr.splice(index, 1, message);
        Vue.set(state.MESSAGE_LIST, message.sessionId, arr);
      }
    }
  },
  actions: {
  },
  modules: {
  }
})
